<script setup lang="ts">
import { ref, reactive, onMounted, h } from 'vue';
import { NButton, NSpace, NInput, NSelect, NTree, NCard, NTag, NPopconfirm, useMessage } from 'naive-ui';
import type { TreeOption } from 'naive-ui';
import { fetchTagTree, deleteTag, type DataTag } from '@/service/api/dataplatform/tag';
import TagOperateDrawer from './modules/tag-operate-drawer.vue';
import TagStatisticsModal from './modules/tag-statistics-modal.vue';

const message = useMessage();

const loading = ref(false);
const treeData = ref<TreeOption[]>([]);
const selectedKeys = ref<string[]>([]);
const expandedKeys = ref<string[]>([]);

const searchParams = reactive({
  tagName: '',
  tagType: '',
  projectId: undefined as number | undefined
});

const tagTypeOptions = [
  { label: '全部', value: '' },
  { label: '业务标签', value: 'BUSINESS' },
  { label: '技术标签', value: 'TECHNICAL' },
  { label: '质量标签', value: 'QUALITY' }
];

// 抽屉和弹窗
const operateDrawerRef = ref<InstanceType<typeof TagOperateDrawer>>();
const statisticsModalRef = ref<InstanceType<typeof TagStatisticsModal>>();

/**
 * 加载标签树
 */
async function loadTagTree() {
  loading.value = true;
  try {
    const { data } = await fetchTagTree(searchParams.projectId);
    treeData.value = convertToTreeOptions(data || []);
  } catch (error) {
    message.error('加载标签树失败');
  } finally {
    loading.value = false;
  }
}

/**
 * 转换为树形选项
 */
function convertToTreeOptions(tags: DataTag[]): TreeOption[] {
  return tags.map(tag => ({
    key: String(tag.id),
    label: tag.tagName,
    prefix: () => renderTagPrefix(tag),
    suffix: () => renderTagSuffix(tag),
    children: tag.children ? convertToTreeOptions(tag.children) : undefined,
    tag
  }));
}

/**
 * 渲染标签前缀
 */
function renderTagPrefix(tag: DataTag) {
  return h(NTag, {
    type: getTagTypeColor(tag.tagType),
    size: 'small',
    round: true
  }, {
    default: () => tag.tagType === 'BUSINESS' ? '业务' : tag.tagType === 'TECHNICAL' ? '技术' : '质量'
  });
}

/**
 * 渲染标签后缀
 */
function renderTagSuffix(tag: DataTag) {
  return h(NSpace, { size: 'small' }, {
    default: () => [
      h(NTag, { size: 'small', type: 'info' }, {
        default: () => `使用 ${tag.usageCount || 0}`
      }),
      h(NTag, { size: 'small', type: 'success' }, {
        default: () => `资产 ${tag.assetCount || 0}`
      })
    ]
  });
}

/**
 * 获取标签类型颜色
 */
function getTagTypeColor(type: string) {
  const colorMap: Record<string, any> = {
    BUSINESS: 'primary',
    TECHNICAL: 'info',
    QUALITY: 'warning'
  };
  return colorMap[type] || 'default';
}

/**
 * 搜索
 */
function handleSearch() {
  loadTagTree();
}

/**
 * 重置
 */
function handleReset() {
  searchParams.tagName = '';
  searchParams.tagType = '';
  searchParams.projectId = undefined;
  loadTagTree();
}

/**
 * 添加标签
 */
function handleAdd(parentId?: number) {
  operateDrawerRef.value?.open('add', undefined, parentId);
}

/**
 * 编辑标签
 */
function handleEdit(tag: DataTag) {
  operateDrawerRef.value?.open('edit', tag.id);
}

/**
 * 删除标签
 */
async function handleDelete(tag: DataTag) {
  try {
    await deleteTag([tag.id!]);
    message.success('删除成功');
    loadTagTree();
  } catch (error) {
    message.error('删除失败');
  }
}

/**
 * 查看统计
 */
function handleStatistics() {
  statisticsModalRef.value?.open();
}

/**
 * 树节点点击
 */
function handleNodeClick(keys: string[], option: TreeOption[]) {
  if (option.length > 0) {
    const tag = (option[0] as any).tag as DataTag;
    selectedKeys.value = keys;
  }
}

/**
 * 树节点右键菜单
 */
function handleNodeContextMenu(key: string, option: TreeOption) {
  const tag = (option as any).tag as DataTag;
  // TODO: 显示右键菜单
}

onMounted(() => {
  loadTagTree();
});

</script>

<template>
  <div class="h-full flex flex-col">
    <!-- 搜索栏 -->
    <NCard :bordered="false" class="mb-4">
      <NSpace :vertical="false" :size="16">
        <NInput
          v-model:value="searchParams.tagName"
          placeholder="标签名称"
          clearable
          style="width: 200px"
        />
        <NSelect
          v-model:value="searchParams.tagType"
          :options="tagTypeOptions"
          placeholder="标签类型"
          clearable
          style="width: 150px"
        />
        <NButton type="primary" @click="handleSearch">
          <template #icon>
            <icon-ic-round-search />
          </template>
          搜索
        </NButton>
        <NButton @click="handleReset">
          <template #icon>
            <icon-ic-round-refresh />
          </template>
          重置
        </NButton>
        <NButton type="primary" @click="handleAdd()">
          <template #icon>
            <icon-ic-round-add />
          </template>
          新增标签
        </NButton>
        <NButton type="info" @click="handleStatistics">
          <template #icon>
            <icon-ic-round-bar-chart />
          </template>
          标签统计
        </NButton>
      </NSpace>
    </NCard>

    <!-- 标签树 -->
    <NCard :bordered="false" class="flex-1">
      <NTree
        :data="treeData"
        :loading="loading"
        :selected-keys="selectedKeys"
        :expanded-keys="expandedKeys"
        block-line
        selectable
        @update:selected-keys="handleNodeClick"
        @update:expanded-keys="(keys) => (expandedKeys = keys)"
      >
        <template #suffix="{ option }">
          <NSpace :size="8">
            <NButton
              size="small"
              type="primary"
              text
              @click.stop="handleAdd((option as any).tag.id)"
            >
              <template #icon>
                <icon-ic-round-add />
              </template>
            </NButton>
            <NButton
              size="small"
              type="info"
              text
              @click.stop="handleEdit((option as any).tag)"
            >
              <template #icon>
                <icon-ic-round-edit />
              </template>
            </NButton>
            <NPopconfirm @positive-click="handleDelete((option as any).tag)">
              <template #trigger>
                <NButton size="small" type="error" text @click.stop>
                  <template #icon>
                    <icon-ic-round-delete />
                  </template>
                </NButton>
              </template>
              确定删除该标签吗？
            </NPopconfirm>
          </NSpace>
        </template>
      </NTree>
    </NCard>

    <!-- 操作抽屉 -->
    <TagOperateDrawer ref="operateDrawerRef" @success="loadTagTree" />

    <!-- 统计弹窗 -->
    <TagStatisticsModal ref="statisticsModalRef" />
  </div>
</template>
